package swdemo;

import java.net.* ;
import java.io.IOException;
import swdemo.log;

// 控制udp收发的类
class udpcontrol {
	// UDP 接收的缓冲区大小
	private static final int RCV_BUFSZ = 100;

	private int port;
	private InetAddress host;
    private DatagramSocket dataSocket;

	public udpcontrol(String ip, int pt) {
        try {
			log.d(ip);
			host = InetAddress.getByName(ip);
			port = pt;
            dataSocket = new DatagramSocket(port);

			// 阻塞方式接收，等待的时延
			dataSocket.setSoTimeout(1000 ) ;
			
        } catch (SocketException se) {
            se.printStackTrace();
        } catch (IOException ie) {
            ie.printStackTrace();
        }
	}

	// 发送函数，没啥说的
	public void send(byte[] data) {
		try {
			log.d("send %d byte\n", data.length);
			for (int i = 0; i < data.length; i++) {
				log.d("%x ", data[i]);
			}
			log.d("\n");
			DatagramPacket packet = new DatagramPacket( data, data.length,
														host, port) ;

			dataSocket.send(packet) ;
		} catch (SocketException se) {
            se.printStackTrace();
		} catch (IOException ie) {
            ie.printStackTrace();
        }
	}

	// 接收函数，注意是阻塞的接收方式
	// 目前没有做非阻塞的方式。因为网络拓扑很简单，预计正常情况下不会出现明显时延
	// （至少sw板子上是没有的）
	public byte[] recv() {
		int sz;
		byte[] receiveData = new byte[RCV_BUFSZ];

		try {
			DatagramPacket receivePacket = new DatagramPacket(receiveData,
															  receiveData.length);
			dataSocket.receive(receivePacket); // 阻塞调用
			log.d("receive %d byte\n", receivePacket.getLength());
			for (int i = 0; i < receivePacket.getLength(); i++) {
				log.d("%x ", receiveData[i]);
			}
			log.d("\n");
			
			if ((sz = receivePacket.getLength()) < RCV_BUFSZ ) {
				byte[] tmp = new byte[sz];
				System.arraycopy(receiveData, 0, tmp, 0, sz);

				return tmp;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return receiveData;
	}
	
}
